package com.xinsoft.controller.mes;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinsoft.aop.ano.SysLog;
import com.xinsoft.common.BusinessType;
import com.xinsoft.common.Response;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.MesCraftDTO;
import com.xinsoft.entity.dto.MesCraftParam;
import com.xinsoft.entity.po.*;
import com.xinsoft.entity.vo.CusDevTestPointVo;
import com.xinsoft.entity.vo.CusTestPointVo;
import com.xinsoft.entity.vo.MesCraftUnionVO;
import com.xinsoft.entity.vo.MesCraftVo;
import com.xinsoft.service.*;
import com.xinsoft.utils.TokenUtil;
import com.xinsoft.validator.ValidatorUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName MesCraftController
 * @Description 工艺路线
 * @Author Li9527
 * @Date 2023-7-17 15:43:16
 * @Version 1.0
 */
@RestController
@RequestMapping("/mes/craft")
@Api(value = "MesCraftController", tags = {"工艺路线控制层"})
public class MesCraftController {

    @Autowired
    private MesCraftService craftService;

    @Autowired
    private SysFileHisService fileHisService;

    @Autowired
    SysUserService userService;

    @Autowired
    MesCraftProcessRefService processRefService;

    @Autowired
    CusDeviceService deviceService;

    @Autowired
    MesCraftCheckRefService checkRefService;

    @Autowired
    MesProcessTestpointService testpointService;

    @Autowired
    MesProcessService processService;

    @Autowired
    CusTestPointService cusTestPointService;

    @Autowired
    QuaCheckItemService checkItemService;

    @Autowired
    MesCraftDeviceService craftDeviceService;

    @Autowired
    MesCarftTeamUserService carftTeamUserService;

    @Autowired
    MesCraftMaterialRefService craftMaterialRefService;

    @Autowired
    MesCraftMaterialService mesCraftMaterialService;

    @Autowired
    MesDocumentService mesDocumentService;

    @Autowired
    SysMaterialService materialService;

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 工艺路线-暂存
     * @Date 2023/5/17 9:57
     * @params dept
     **/
    @SysLog(title = "工艺路线-保存", businessType = BusinessType.INSERT)
    @ApiOperation("保存")
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> add(@RequestBody MesCraftDTO mesCraftDTO) {
        // 参数校验
        ValidatorUtils.validateEntity(mesCraftDTO);
        // 默认待审核
        mesCraftDTO.setAuditStatus(Const.AUDIT_STATUS_WAIT);
        MesCraft oldCraft = craftService.getOne(new QueryWrapper<MesCraft>().eq("craft_name", mesCraftDTO.getCraftName()));
        if (oldCraft != null) {
            return Response.fail("该工艺路线已存在,请不要重复添加");
        }
        craftService.create(mesCraftDTO);
        return Response.succeed();
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 更新
     * @Date 2023/5/17 9:57
     * @params dept
     **/
    @ApiOperation("编辑")
    @SysLog(title = "工艺路线-编辑", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> edit(@RequestBody MesCraftDTO MesCraftDTO) {
        // 参数校验
        ValidatorUtils.validateEntity(MesCraftDTO);
        MesCraft oldCraft = craftService.getOne(new QueryWrapper<MesCraft>().eq("craft_name", MesCraftDTO.getCraftName()));
        if (oldCraft != null && !oldCraft.getId().equals(MesCraftDTO.getId())) {
            return Response.fail("该工艺路线已存在,请不要重复添加");
        }
        craftService.edit(MesCraftDTO);
        return Response.succeed();
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 获取详情
     * @Date 2023/5/17 9:57
     * @params id
     **/
    @ApiOperation("获取详情")
    @GetMapping("/detail")
    public Response<?> detail(@RequestParam(value = "id", defaultValue = "", required = true) Integer id) {
        MesCraftVo mesCraftVo = new MesCraftVo();
        MesCraft mesCraft = craftService.getById(id);
        BeanUtil.copyProperties(mesCraft,mesCraftVo);
        List<MesCraftUnionVO> craftUnionVOList = new ArrayList<>();
        List<MesCraftProcessRef> list = processRefService.list(new QueryWrapper<MesCraftProcessRef>().eq("craft_id",id));
        for (int i = 0; i < list.size(); i++) {
            MesCraftUnionVO mesCraftUnionVO = new MesCraftUnionVO();
            MesCraftProcessRef mesCraftProcessRef = list.get(i);
            BeanUtil.copyProperties(list.get(i),mesCraftUnionVO);
            MesProcess mesProcess = processService.getById(mesCraftProcessRef.getProcessId());
            if (mesProcess != null) {
                mesCraftUnionVO.setProcessNo(mesProcess.getProcessNo());
                mesCraftUnionVO.setProcessName(mesProcess.getProcessName());
            }
            // 追加班组
            List<MesCarftTeamUser> teamUserList = carftTeamUserService.list(new QueryWrapper<MesCarftTeamUser>().eq("craft_process_id",mesCraftProcessRef.getId()));
            mesCraftUnionVO.setTeamUserRefList(teamUserList);
            // 追加工序投料&产出
            List<MesCraftMaterialRef> craftMaterialRefList = craftMaterialRefService.list(new QueryWrapper<MesCraftMaterialRef>().eq("craft_process_id",mesCraftProcessRef.getId()));
            // 翻译物料名字
            for (int j = 0; j < craftMaterialRefList.size(); j++) {
                SysMaterial sysMaterial = materialService.getById(craftMaterialRefList.get(j).getMaterialId());
                if(sysMaterial != null){
                    craftMaterialRefList.get(j).setMaterialName(sysMaterial.getMaterialName());
                }
            }
            mesCraftUnionVO.setMaterialRefList(craftMaterialRefList);
            // 追加加工工装
            List<MesCraftMaterial> mesCraftMaterialList = mesCraftMaterialService.list(new QueryWrapper<MesCraftMaterial>().eq("craft_process_id",mesCraftProcessRef.getId()));
            // 翻译物料名字
            for (int j = 0; j < craftMaterialRefList.size(); j++) {
                SysMaterial sysMaterial = materialService.getById(craftMaterialRefList.get(j).getMaterialId());
                if(sysMaterial != null){
                    craftMaterialRefList.get(j).setMaterialName(sysMaterial.getMaterialName());
                }
            }
            mesCraftUnionVO.setMaterialList(mesCraftMaterialList);
            // 追加sop
            List<MesDocument> documentList = mesDocumentService.list(new QueryWrapper<MesDocument>().eq("mes_id", mesCraftProcessRef.getId())
            .eq("mes_type",Const.FileType.BACK_FILE));
            List<Integer> fileIds = new ArrayList<>();
            for (int y = 0; y < documentList.size(); y++) {
                fileIds.add(documentList.get(y).getDocumentId());
            }
            if (documentList.size() > 0) {
                List<SysFileHis> sysFileHis = fileHisService.listByIds(fileIds);
                mesCraftUnionVO.setSysFileHisList(sysFileHis);
            }
            // 追加工序设备组对象集合
            List<MesCraftDevice> craftDeviceList = craftDeviceService.list(new QueryWrapper<MesCraftDevice>().eq("craft_process_id",mesCraftProcessRef.getId()));
            mesCraftUnionVO.setCraftDeviceList(craftDeviceList);
            for (int j = 0; j < mesCraftUnionVO.getCraftDeviceList().size(); j++) {
                MesCraftDevice mesCraftDevice = mesCraftUnionVO.getCraftDeviceList().get(j);
                List<MesCraftCheckRef> checkRef = checkRefService.list(new QueryWrapper<MesCraftCheckRef>().eq("craft_device_id",mesCraftDevice.getId()));
                if (checkRef.size() > 0) {
                    for (int k = 0; k < checkRef.size(); k++) {
                        QuaCheckItem quaCheckItem = checkItemService.getById(checkRef.get(k).getCheckItemId());
                        if (quaCheckItem != null) {
                            checkRef.get(k).setCheckItemCode(quaCheckItem.getCheckItemCode());
                            checkRef.get(k).setCheckItemName(quaCheckItem.getCheckItemName());
                            checkRef.get(k).setCheckMethod(quaCheckItem.getCheckMethod());
                        }
                    }
                }
                List<MesProcessTestpoint> testpoint = testpointService.list(new QueryWrapper<MesProcessTestpoint>().eq("craft_device_id",mesCraftDevice.getId()));
                List<CusTestPointVo> pointList = new ArrayList<>();
                if(testpoint.size() > 0){
                    for (int w = 0; w < testpoint.size(); w++) {
                        // 侵入测点对象集合，因为mes项目service无法调用cus设备的service
                        CusDevTestPointVo cusDevTestPoint = cusTestPointService.getCusTestPoint(testpoint.get(j).getTestPointId());
                        CusTestPointVo cusTestPoint = new CusTestPointVo();
                        BeanUtils.copyProperties(cusDevTestPoint,cusTestPoint);
                        pointList.add(cusTestPoint);
                    }
                }
                mesCraftUnionVO.getCraftDeviceList().get(j).setCraftCheckRefList(checkRef);
                mesCraftUnionVO.getCraftDeviceList().get(j).setTestPointVoList(pointList);
            }
            craftUnionVOList.add(mesCraftUnionVO);
        }
        mesCraftVo.setMesCraftUnionList(craftUnionVOList);
        return Response.succeed(mesCraftVo);
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 删除
     * @Date 2023/5/12 9:20
     * @params ids
     **/
    @ApiOperation("删除")
    @SysLog(title = "工艺路线-删除", businessType = BusinessType.DELETE)
    @PostMapping("/del")
    public Response<?> del(@RequestBody List<Integer> ids) {
        for (int i = 0; i < ids.size(); i++) {
            MesCraft MesCraft = craftService.getById(ids.get(i));
            if (MesCraft != null && MesCraft.getAuditStatus().equals(Const.AUDIT_STATUS_NORMAL)) {
                return Response.fail("存在已审核工艺路线，不允许删除");
            }
        }
        craftService.removeByIds(ids);
        return Response.succeed();
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 批量审核
     * @Date 2023/5/12 9:20
     * @params ids
     **/
    @ApiOperation("工艺路线-批量审核")
    @SysLog(title = "工艺路线-批量审核", businessType = BusinessType.UPDATE)
    @PostMapping("/auditBatch")
    public Response<?> auditBacth(@RequestBody List<Integer> ids) {
        Integer auditId = TokenUtil.getUser().getId();
        List<MesCraft> list = craftService.list(new QueryWrapper<MesCraft>().in("id", ids));
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setAuditStatus(Const.AUDIT_STATUS_NORMAL);
            list.get(i).setAuditId(auditId);
        }
        craftService.updateBatchById(list);
        return Response.succeed();
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 批量反审核
     * @Date 2023/5/12 9:20
     * @params ids
     **/
    @ApiOperation("工艺路线-批量反审核")
    @SysLog(title = "工艺路线-批量反审核", businessType = BusinessType.UPDATE)
    @PostMapping("/unAuditBatch")
    public Response<?> unAuditBatch(@RequestBody List<Integer> ids) {
        List<MesCraft> list = craftService.list(new QueryWrapper<MesCraft>().in("id", ids));
        Integer auditId = TokenUtil.getUser().getId();
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setAuditStatus(Const.AUDIT_STATUS_WAIT);
            list.get(i).setAuditId(auditId);
        }
        craftService.updateBatchById(list);
        return Response.succeed();
    }

    /**
     * @return com.xinsoft.common.Response<?>
     * @Author Li9527
     * @Description 工艺路线-分页
     * @Date 2023/5/18 10:51
     * @params param
     **/
    @PostMapping("/pageList")
    public Response<?> pageList(@Valid @RequestBody MesCraftParam param) {
        return Response.succeed(craftService.findPageListByParam(param));
    }

    /**
     * 导入
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/import")
    @ResponseBody
    public Response<?> importExcel(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        return Response.succeed(craftService.importExcel(multipartFile));
    }

}
